#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time

import client_util
from datetime import datetime
from datetime import timedelta
import config
import json
import requests
import mysql_client
import schedule

datetime_parttern = "%Y%m%d%H0000"
tableName = 'surf_chn_mul_hor'
startTimeStr = '20220101000000'
endTimeStr = '20230101000000'
dataCode = 'SURF_CHN_MUL_HOR'
interfaceId = 'getSurfEleInRegionByTime'


'''
    中国地面逐小时全要素数据表
'''
def getSurfEleInRegionByTime(db):

    #从数据库中查询
    lastData = mysql_client.select_data("SELECT times, try_times FROM {} WHERE times = (SELECT MAX(times) FROM {}) LIMIT 1".format(tableName, tableName))
    print(lastData)
    maxTimes = 0
    tryTimes = 0
    delta = 1

    if len(lastData) == 0:
        maxTimes = config.start_times
        tryTimes = 0
    else:
        maxTimes = lastData[0][u'times']
        tryTimes = lastData[0][u'try_times']

    if tryTimes > 4:
        delta = 2

    print('before maxTimes: {}, tryTimes: {}'.format(maxTimes, tryTimes))
    lastMaxDatetime = datetime.strptime(str(maxTimes), datetime_parttern)

    startDatetime = lastMaxDatetime + timedelta(hours=delta)
    formatted_time = startDatetime.strftime(datetime_parttern)

    print('after maxTimes: {}, tryTimes: {}'.format(maxTimes, tryTimes))
    doGetSurfEleInRegionByTime(formatted_time, tryTimes)


def scheduleJob(db):

    #获取当前时间
    currentTime = datetime.now()
    times = currentTime - timedelta(hours=24)
    formatted_time = times.strftime(datetime_parttern)
    print("formatted_time: {}".format(formatted_time))
    result = mysql_client.select_data("select * from {} where times={}".format(tableName, formatted_time))
    print(result)
    if not result:
        doGetSurfEleInRegionByTime(formatted_time, 0, db)

def initSurfEleInRegionByTime(db):

    '''
    初始化
    :return:
    '''

    startTime = datetime.strptime(startTimeStr, datetime_parttern)
    endTime = datetime.strptime(endTimeStr, datetime_parttern)

    while startTime < endTime:
        print(startTime)
        formatted_time = startTime.strftime(datetime_parttern)
        doGetSurfEleInRegionByTime(formatted_time, 1, db)
        # 时间+1小时
        startTime = startTime + timedelta(hours=1)


def doGetSurfEleInRegionByTime(times, tryTimes, db):
    '''
        中国地面分钟数据
    '''

    dic = {}
    dic['interfaceId'] = interfaceId
    dic['dataCode'] = dataCode
    dic['elements'] = 'Cnty,Station_Name,City,Town,Country,Station_Id_C,Lat,Lon,Alti,Datetime,Year,Mon,Day,Hour,Station_Id_d,PRS_Sensor_Alti,WIN_S_Sensor_Heigh,TEM_RHU_Sensor_Heigh,VIS_Sensor_Heigh,Station_Type,V08010,PRS,PRS_Sea,PRS_Change_3h,PRS_Change_24h,PRS_Max,PRS_Max_OTime,PRS_Min,PRS_Min_OTime,TEM,TEM_Max,TEM_Max_OTime,TEM_Min,TEM_Min_OTime,TEM_ChANGE_24h,TEM_Max_24h,TEM_Min_24h,DPT,RHU,RHU_Min,RHU_Min_OTIME,VAP,PRE_1h,PRE_3h,PRE_6h,PRE_12h,PRE_24h,PRE_Arti_Enc_CYC,PRE,EVP_Big,WIN_D_Avg_2mi,WIN_S_Avg_2mi,WIN_D_Avg_10mi,WIN_S_Avg_10mi,WIN_D_S_Max,WIN_S_Max,WIN_S_Max_OTime,WIN_D_INST,WIN_S_INST,WIN_D_INST_Max,WIN_S_Inst_Max,WIN_S_INST_Max_OTime,WIN_D_Inst_Max_6h,WIN_S_Inst_Max_6h,WIN_D_Inst_Max_12h,WIN_S_Inst_Max_12h,GST,GST_Max,GST_Max_Otime,GST_Min,GST_Min_OTime,GST_Min_12h,GST_5cm,GST_10cm,GST_15cm,GST_20cm,GST_40Cm,GST_80cm,GST_160cm,GST_320cm,LGST,LGST_Max,LGST_Max_OTime,LGST_Min,LGST_Min_OTime,VIS_HOR_1MI,VIS_HOR_10MI,VIS_Min,VIS_Min_OTime,VIS,WEP_Now,WEP_Past_CYC,WEP_Past_1,WEP_Past_2,SCO,Snow_Depth,Snow_PRS,FRS_1st_Top,FRS_1st_Bot,FRS_2nd_Top,FRS_2nd_Bot,V13196,V02175,V20214,EICE,EICED_NS,EICET_NS,EICEW_NS,EICED_WE,EICET_WE,EICEW_WE,WIN_D,WIN_S,WEP_Record,'
    dic['dataFormat'] = 'json'
    dic['times'] = times
    dic['adminCodes'] = config.adminCodes

    httpurl = client_util.getTqUrl(dic)
    response = requests.get(url=httpurl)

    print('statusCode: {}'.format(response.status_code))
    if response.status_code != 200:
        insert_error(times, tryTimes, response.status_code, -1, db)
        return

    if response.content.isspace():
        insert_error(times, tryTimes, response.status_code, -2, db)
        return

    result = json.loads(response.content)
    returnCode = result['returnCode']
    print('resultCode: {}'.format(returnCode))

    if returnCode != '0':
        print('returnCode not available, code: {}'.format(returnCode))
        insert_error(times, tryTimes, response.status_code, returnCode, db)
        return

    if result['rowCount'] == '0':
        print('rowCount is 0')
        insert_error(times, tryTimes, response.status_code, returnCode, db)
        return

    DS = result['DS']

    for i in range(len(DS)):
        data = DS[i]

        tableData = {
            'times': times,
            'try_times': tryTimes,
            'status_code': response.status_code,
            'returnCode': returnCode,
            'Cnty': data[u'Cnty'].encode('utf8'),
            'Station_Name': data[u'Station_Name'].encode('utf8'),
            'City': data[u'City'].encode('utf8'),
            'Town': data[u'Town'].encode('utf8'),
            'Country': data[u'Country'].encode('utf8'),
            'Station_Id_C': data[u'Station_Id_C'].encode('utf8'),
            'Lat': data[u'Lat'].encode('utf8'),
            'Lon': data[u'Lon'].encode('utf8'),
            'Alti': data[u'Alti'].encode('utf8'),
            'Datetime': data[u'Datetime'].encode('utf8'),
            'Year': data[u'Year'].encode('utf8'),
            'Mon': data[u'Mon'].encode('utf8'),
            'Day': data[u'Day'].encode('utf8'),
            'Hour': data[u'Hour'].encode('utf8'),
            'Station_Id_d': data[u'Station_Id_d'].encode('utf8'),
            'PRS_Sensor_Alti': data[u'PRS_Sensor_Alti'].encode('utf8'),
            'WIN_S_Sensor_Heigh': data[u'WIN_S_Sensor_Heigh'].encode('utf8'),
            'TEM_RHU_Sensor_Heigh': data[u'TEM_RHU_Sensor_Heigh'].encode('utf8'),
            'VIS_Sensor_Heigh': data[u'VIS_Sensor_Heigh'].encode('utf8'),
            'Station_Type': data[u'Station_Type'].encode('utf8'),
            'V08010': data[u'V08010'].encode('utf8'),
            'PRS': data[u'PRS'].encode('utf8'),
            'PRS_Sea': data[u'PRS_Sea'].encode('utf8'),
            'PRS_Change_3h': data[u'PRS_Change_3h'].encode('utf8'),
            'PRS_Change_24h': data[u'PRS_Change_24h'].encode('utf8'),
            'PRS_Max': data[u'PRS_Max'].encode('utf8'),
            'PRS_Max_OTime': data[u'PRS_Max_OTime'].encode('utf8'),
            'PRS_Min': data[u'PRS_Min'].encode('utf8'),
            'PRS_Min_OTime': data[u'PRS_Min_OTime'].encode('utf8'),
            'TEM': data[u'TEM'].encode('utf8'),
            'TEM_Max': data[u'TEM_Max'].encode('utf8'),
            'TEM_Max_OTime': data[u'TEM_Max_OTime'].encode('utf8'),
            'TEM_Min': data[u'TEM_Min'].encode('utf8'),
            'TEM_Min_OTime': data[u'TEM_Min_OTime'].encode('utf8'),
            'TEM_ChANGE_24h': data[u'TEM_ChANGE_24h'].encode('utf8'),
            'TEM_Max_24h': data[u'TEM_Max_24h'].encode('utf8'),
            'TEM_Min_24h': data[u'TEM_Min_24h'].encode('utf8'),
            'DPT': data[u'DPT'].encode('utf8'),
            'RHU': data[u'RHU'].encode('utf8'),
            'RHU_Min': data[u'RHU_Min'].encode('utf8'),
            'RHU_Min_OTIME': data[u'RHU_Min_OTIME'].encode('utf8'),
            'VAP': data[u'VAP'].encode('utf8'),
            'PRE_1h': data[u'PRE_1h'].encode('utf8'),
            'PRE_3h': data[u'PRE_3h'].encode('utf8'),
            'PRE_6h': data[u'PRE_6h'].encode('utf8'),
            'PRE_12h': data[u'PRE_12h'].encode('utf8'),
            'PRE_24h': data[u'PRE_24h'].encode('utf8'),
            'PRE_Arti_Enc_CYC': data[u'PRE_Arti_Enc_CYC'].encode('utf8'),
            'PRE': data[u'PRE'].encode('utf8'),
            'EVP_Big': data[u'EVP_Big'].encode('utf8'),
            'WIN_D_Avg_2mi': data[u'WIN_D_Avg_2mi'].encode('utf8'),
            'WIN_S_Avg_2mi': data[u'WIN_S_Avg_2mi'].encode('utf8'),
            'WIN_D_Avg_10mi': data[u'WIN_D_Avg_10mi'].encode('utf8'),
            'WIN_S_Avg_10mi': data[u'WIN_S_Avg_10mi'].encode('utf8'),
            'WIN_D_S_Max': data[u'WIN_D_S_Max'].encode('utf8'),
            'WIN_S_Max': data[u'WIN_S_Max'].encode('utf8'),
            'WIN_S_Max_OTime': data[u'WIN_S_Max_OTime'].encode('utf8'),
            'WIN_D_INST': data[u'WIN_D_INST'].encode('utf8'),
            'WIN_S_INST': data[u'WIN_S_INST'].encode('utf8'),
            'WIN_D_INST_Max': data[u'WIN_D_INST_Max'].encode('utf8'),
            'WIN_S_Inst_Max': data[u'WIN_S_Inst_Max'].encode('utf8'),
            'WIN_S_INST_Max_OTime': data[u'WIN_S_INST_Max_OTime'].encode('utf8'),
            'WIN_D_Inst_Max_6h': data[u'WIN_D_Inst_Max_6h'].encode('utf8'),
            'WIN_S_Inst_Max_6h': data[u'WIN_S_Inst_Max_6h'].encode('utf8'),
            'WIN_D_Inst_Max_12h': data[u'WIN_D_Inst_Max_12h'].encode('utf8'),
            'WIN_S_Inst_Max_12h': data[u'WIN_S_Inst_Max_12h'].encode('utf8'),
            'GST': data[u'GST'].encode('utf8'),
            'GST_Max': data[u'GST_Max'].encode('utf8'),
            'GST_Max_Otime': data[u'GST_Max_Otime'].encode('utf8'),
            'GST_Min': data[u'GST_Min'].encode('utf8'),
            'GST_Min_OTime': data[u'GST_Min_OTime'].encode('utf8'),
            'GST_Min_12h': data[u'GST_Min_12h'].encode('utf8'),
            'GST_5cm': data[u'GST_5cm'].encode('utf8'),
            'GST_10cm': data[u'GST_10cm'].encode('utf8'),
            'GST_15cm': data[u'GST_15cm'].encode('utf8'),
            'GST_20cm': data[u'GST_20cm'].encode('utf8'),
            'GST_40Cm': data[u'GST_40Cm'].encode('utf8'),
            'GST_80cm': data[u'GST_80cm'].encode('utf8'),
            'GST_160cm': data[u'GST_160cm'].encode('utf8'),
            'GST_320cm': data[u'GST_320cm'].encode('utf8'),
            'LGST': data[u'LGST'].encode('utf8'),
            'LGST_Max': data[u'LGST_Max'].encode('utf8'),
            'LGST_Max_OTime': data[u'LGST_Max_OTime'].encode('utf8'),
            'LGST_Min': data[u'LGST_Min'].encode('utf8'),
            'LGST_Min_OTime': data[u'LGST_Min_OTime'].encode('utf8'),
            'VIS_HOR_1MI': data[u'VIS_HOR_1MI'].encode('utf8'),
            'VIS_HOR_10MI': data[u'VIS_HOR_10MI'].encode('utf8'),
            'VIS_Min': data[u'VIS_Min'].encode('utf8'),
            'VIS_Min_OTime': data[u'VIS_Min_OTime'].encode('utf8'),
            'VIS': data[u'VIS'].encode('utf8'),
            'WEP_Now': data[u'WEP_Now'].encode('utf8'),
            'WEP_Past_CYC': data[u'WEP_Past_CYC'].encode('utf8'),
            'WEP_Past_1': data[u'WEP_Past_1'].encode('utf8'),
            'WEP_Past_2': data[u'WEP_Past_2'].encode('utf8'),
            'SCO': data[u'SCO'].encode('utf8'),
            'Snow_Depth': data[u'Snow_Depth'].encode('utf8'),
            'Snow_PRS': data[u'Snow_PRS'].encode('utf8'),
            'FRS_1st_Top': data[u'FRS_1st_Top'].encode('utf8'),
            'FRS_1st_Bot': data[u'FRS_1st_Bot'].encode('utf8'),
            'FRS_2nd_Top': data[u'FRS_2nd_Top'].encode('utf8'),
            'FRS_2nd_Bot': data[u'FRS_2nd_Bot'].encode('utf8'),
            'V13196': data[u'V13196'].encode('utf8'),
            'V02175': data[u'V02175'].encode('utf8'),
            'V20214': data[u'V20214'].encode('utf8'),
            'EICE': data[u'EICE'].encode('utf8'),
            'EICED_NS': data[u'EICED_NS'].encode('utf8'),
            'EICET_NS': data[u'EICET_NS'].encode('utf8'),
            'EICEW_NS': data[u'EICEW_NS'].encode('utf8'),
            'EICED_WE': data[u'EICED_WE'].encode('utf8'),
            'EICET_WE': data[u'EICET_WE'].encode('utf8'),
            'EICEW_WE': data[u'EICEW_WE'].encode('utf8'),
            'WIN_D': data[u'WIN_D'].encode('utf8'),
            'WIN_S': data[u'WIN_S'].encode('utf8'),
            'WEP_Record': data[u'WEP_Record'].encode('utf8')
        }

        mysql_client.insert_data(tableData, tableName, db)

def insert_error(times, tryTimes, status_code, returnCode, db):

    """

    :param times:
    :param tryTimes:
    :return:
    """

    tableData = {
        'times': times,
        'try_times': tryTimes + 1,
        'status_code': status_code,
        'returnCode': returnCode
    }

    mysql_client.insert_data(tableData, tableName, db)


def startJob():
    db = mysql_client.connect_db()
    schedule.every().hour.do(scheduleJob, db)

    while True:
        schedule.run_pending()
        time.sleep(1)

    db.close()
    pass


if __name__ == "__main__":
    # db = mysql_client.connect_db()
    # getSurfEleInRegionByTime(db)
    #initSurfEleInRegionByTime(db)
    # db.close()

    startJob()
